package eva.savant.core.view.util

import eva.savant.core.service.NameService
import eva.savant.core.service.EntityService
import eva.savant.business.global.service.QSGlobal

import org.springframework.ui.velocity.VelocityEngineUtils
import org.apache.velocity.app.VelocityEngine
import com.sun.mail.imap.IMAPFolder
import javax.mail.Flags.Flag
import javax.mail.internet.*
import javax.mail.*

public class Email {


  private String dominio, hostInt, hostExt

  private static Email email

  private Session session


  private Email() {

    def eService= (EntityService) AppContext.applicationContext.getBean(NameService.ENTITY_SERVICE)


    def props = new Properties()

    props.setProperty('mail.transport.protocol',eService.getEntity(QSGlobal.parametroVal,'mail.transport.protocol') + '')

    props.setProperty('mail.store.protocol',    eService.getEntity(QSGlobal.parametroVal,'mail.store.protocol') + '')

    props.setProperty('mail.smtp.host',         eService.getEntity(QSGlobal.parametroVal,'mail.smtp.host') + '')


    dominio= eService.getEntity(QSGlobal.parametroVal,'mail.dominio') + ''

    hostInt= eService.getEntity(QSGlobal.parametroVal,'mail.smtp.host') + ''

    hostExt= eService.getEntity(QSGlobal.parametroVal,'mail.smtp.host.externo') + ''


    session = Session.getDefaultInstance(props,null)
  }

  public static synchronized Email getInstance() {

    return email == null? email= new Email() : email
  }

  public void sendMail(String title, String name, Map model, String mailFrom, String mailTo) throws Exception {

    def velocityEngine = (VelocityEngine) FacesUtils.getSpringBean('velocityEngine')

    def message = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, name, model)

    sendMail(title, message ,mailFrom, mailTo)
  }

  public void sendMail(String title, String message, String mailFrom, String mailTo) throws Exception {

    def type= message.startsWith('<HTML>') || message.startsWith('<html>') ? 'text/html' : 'text/plain'

    def host= mailTo.endsWith(dominio)? hostInt : hostExt

    def transport= null

    try {

      def mm = new MimeMessage(session)

      mm.from= new InternetAddress(mailFrom)

      mm.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo))

      mm.subject= title

      mm.setContent(message, type+'; charset=\"UTF-8\"')

      transport= session.transport

      transport.connect(host,null,null)

      transport.sendMessage(mm, mm.allRecipients)

    } catch (Exception e) { e.printStackTrace(); throw e;

    } finally { if(transport != null) transport.close() }

  }

  public List<String[]> open(String server, String username, String password) throws Exception {

    def store = session.getStore('imap')


    store.connect(server,username,password)


    def inbox = (IMAPFolder) store.getFolder('Inbox')


    inbox.open(Folder.READ_WRITE)


    def result= new ArrayList<String[]>()

      
    for(int i=1; i<=inbox.messageCount; i++) {

    def message= inbox.getMessage(i)

    if(message.flags.contains(Flag.SEEN)) continue

    message.setFlag(Flag.SEEN,true)

    def content= getMessage(message)

    def address= ((InternetAddress[])message.from)[0].address

    result.add([address,message.subject,content] as String[]) }


    inbox.close(true)

    return result
  }

  public String getMessage(Part part) {

    if(part.isMimeType('multipart/*')) {

      def result= ''

      def mp= (Multipart) part.content

      for (int i= 0; i < mp.count; i++)

      result= result + getMessage(mp.getBodyPart(i))

      return result

    } else

    if(part.isMimeType('text/plain')) return part.content + '' else return ''

  }

}
